import { BindDeviceComponent } from './../bindDevice/bindDevice.component';
import { NavController } from 'ionic-angular';
import { MdSnackBar } from '@angular/material';
import { NavigateService } from './../../service/navigate.service';
import { Component, OnInit, OnDestroy, HostListener } from '@angular/core';
import { Authentication } from "../../service/index";
import { MessageBoxService, GrowlMessageType } from "../../component/index";
import { loadingMask } from './../../component/decorators';

@Component({
    //moduleId: module.id,
    selector: 'login',
    templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
    constructor(
        private router: NavigateService,
        private authSvr: Authentication,
        private msgSvr: MessageBoxService,
        public snackBar: MdSnackBar,
        public navCtrl: NavController
    ) { }
    title: string = "店铺名称";
    username = "";
    password = "";
    store;

    @HostListener('document:keyup', ['$event'])
    onKeyUp(ev: KeyboardEvent) {
        if (ev.keyCode == 13) {
            this.login();
        }
    }

    ngOnInit() {
        //TODO:会出现闪现界面
        // if (this.authSvr.StoreOwner && this.authSvr.CurrentStore) {
        //     this.router.navigate(["checkEnv"]);
        // }
        if (this.authSvr.CurrentStore) {
            this.store = this.authSvr.CurrentStore;
        }
    }

    @loadingMask()
    async login() {
        try {
            let r: any = await this.authSvr.storeLogin(this.username, this.password);
            if (r && r.result == false) {
                return this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, r.msg ? r.msg : "登录失败");
            }
            if (r.token) {
                this.authSvr.Token = r.token;
            }
            // this.router.navigate(["bindDevice"]);
            this.navCtrl.setRoot(BindDeviceComponent);
        } catch (error) {
            this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, error ? error : "登录失败");
        }
    }
}
